﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;
using Xenta.Utils;
using Xenta.Attributes;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.System.Controllers
{
    [Authenticate, InRole("ADMIN")]
    public sealed class ImportExportController : ExtController
    {
        #region GET/POST Actions

        [HttpGet, RestoreState]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost, PersistState]
        public ActionResult Import(Guid formatID, 
            string name, 
            IDictionary<String, String> properties, 
            HttpPostedFileBase file,
            string returnUrl)
        {
            if(file != null)
            {
                try
                {
                    int result = 0;

                    using(var stream = file.InputStream)
                    {
                        result = Svc.ImportData(name, properties, formatID, stream);
                    }
                    TempData.PersistObject("ImportResult", result);
                }
                catch(Exception ex)
                {
                    ModelState.AddModelError("API", ex);
                }
            }
            if(!String.IsNullOrWhiteSpace(returnUrl))
                return Redirect(returnUrl);
            return RedirectToAction(Loc.Act("Index"));
        }

        [HttpPost, PersistState]
        public ActionResult Export(Guid formatID,
            string name,
            IDictionary<String, String> properties,
            string returnUrl)
        {
            try
            {
                Stream dataStream = null;
                string mimeType = Svc.ExportData(name, properties, formatID, out dataStream);
                string fileExt = MimeTypeHelper.TypeToExt(mimeType);
                string fileName = String.Format("{0}.{1}", name, fileExt);

                return File(dataStream, mimeType, fileName);
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            if(!String.IsNullOrWhiteSpace(returnUrl))
                return Redirect(returnUrl);
            return RedirectToAction(Loc.Act("Index"));
        }

        [HttpPost]
        public ActionResult Formats()
        {
            dynamic m = Svc.ProcessOperation("ListImportExportFormats");
            var data = new List<Object>();

            foreach(var i in m)
            {
                data.Add(new
                {
                    id = JDM.Guid(i.ID),
                    value = JDM.String(i.Name)
                });
            }
            return Json(data.ToArray());
        }

        #endregion
    }
}
